package com.zhxs.nfcscan.utils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;

import com.zhxs.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

public class NFCUtil {
    private NfcAdapter nfcAdapter = null;
    private PendingIntent mPendingIntent = null;
    private IntentFilter[] intentFilters =null;

    private String[][] mTechList = null;

    public boolean initNfc(Activity activity){
        try {
            // 获取NFC适配器
            nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
            if (nfcAdapter == null) {
                LogUtil.e( "设备不支持NFC");
                return false;
            }
            if (!nfcAdapter.isEnabled()) {
                LogUtil.e( "NFC未开启");
                return false;
            }
            mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_MUTABLE);

            // 创建Intent过滤器，用于识别NDEF格式的标签
            IntentFilter ndefIntentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
            try {
                ndefIntentFilter.addDataType("text/plain");
                ndefIntentFilter.addDataType("application/*");
            } catch (IntentFilter.MalformedMimeTypeException e) {
                LogUtil.e("NFCUtil", "MIME类型格式错误", e);
            }
            // 创建TAG_DISCOVERED的Intent过滤器（作为后备）
            IntentFilter tagIntentFilter =new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
            intentFilters = new IntentFilter[]{ndefIntentFilter, tagIntentFilter};
            mTechList = null;
            return true;
        } catch (Exception e) {
            LogUtil.e("NFC初始化失败");
            return false;
        }

    }

        /**
         * 启用NFC前台调度系统
         * @param activity 当前Activity
         */
        public void enableNFCForegroundDispatch(Activity activity) {
            if (nfcAdapter != null) {
                try {
                    // 定义支持的NFC标签技术类型

                    // 启用前台调度系统
                    nfcAdapter.enableForegroundDispatch(activity, mPendingIntent, null , null);
                    LogUtil.d("NFC前台调度系统已启用");
                } catch (Exception e ) {
                    LogUtil.e("启用NFC前台调度系统失败");
                }
            }
        }

    /**
     * 启用NFC前台调度系统
     * @param activity 当前Activity
     */
    public void disableNFCForegroundDispatch(Activity activity) {
        if (nfcAdapter != null) {
            try {
                nfcAdapter.disableForegroundDispatch(activity);
                LogUtil.d(" NFC前台调度系统已禁用");
            } catch (Exception e) {
                LogUtil.e( "禁用NFC前台调度系统失败");
            }
        }
    }


}
